package com.wuyou.md.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {


    @Primary
    @Bean("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        System.out.println("Primary DataSource URL: " + getDataSourceUrl(dataSource));
        return dataSource;
    }

    @Bean("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        System.out.println("Secondary DataSource URL: " + getDataSourceUrl(dataSource));
        return dataSource;
    }

    // 辅助方法，用于调试数据源URL
    private String getDataSourceUrl(DataSource dataSource) {
        try {
            if (dataSource instanceof com.zaxxer.hikari.HikariDataSource) {
                return ((com.zaxxer.hikari.HikariDataSource) dataSource).getJdbcUrl();
            }
            return "Unknown DataSource type";
        } catch (Exception e) {
            return "Error getting URL: " + e.getMessage();
        }
    }
}
